package com.jucai.pppeiyouclient.view.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.baidu.location.BDLocation;
import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jucai.pppeiyouclient.MainActivity;
import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.base.BaseActivity;
import com.jucai.pppeiyouclient.base.BaseApplication;
import com.jucai.pppeiyouclient.base.BaseParam;
import com.jucai.pppeiyouclient.base.BaseTakePhotoActivity;
import com.jucai.pppeiyouclient.base.PermissionListener;
import com.jucai.pppeiyouclient.bean.AccompanyInfoBean;
import com.jucai.pppeiyouclient.comm.CommonData;
import com.jucai.pppeiyouclient.comm.CommonMethod;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.CompressPhoto;
import com.jucai.pppeiyouclient.utils.DateUtil;
import com.jucai.pppeiyouclient.utils.ImageHandleUtils;
import com.jucai.pppeiyouclient.utils.LocationHelper;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.OssUtils;
import com.jucai.pppeiyouclient.utils.TextCheckUtils;
import com.jucai.pppeiyouclient.utils.ToastUtils;
import com.jucai.pppeiyouclient.view.dialog.InitiateDialog;
import com.jucai.pppeiyouclient.view.popup.HeadUploadPopup;

import org.apache.commons.lang3.StringEscapeUtils;
import org.feezu.liuli.timeselector.TimeSelector;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ActivitiesInitiateActivity extends BaseTakePhotoActivity implements Handler.Callback {
    private static final String TAG = "ActivitiesInitiateActivity : ";

    private static final int GET_TITLE = 3001;
    private static final int GET_START_LOC = 3002;
    private static final int GET_END_LOC = 3003;
    private static final int GET_FEE = 3004;
    private static final int GET_VENUE = 3005;

    private static final int TAKE_PHOTO = 2001;
    private static final int CHOOSE_IMAGE = 2002;
    private static final int CROP_IMAGE = 2003;

    private TextView initiateTitle, venue01, initiateStartLoc, initiateEndLoc, initiateStartTime, initiateEndTime,
            initiateUploadImg, initiateAgreement, initiate_venue;
    private ImageButton maxMinus, maxAdd, minMinus, minAdd;
    private EditText maxParticipant, minParticipant, initiateDetailIntro, initiateFee;
    private CheckBox initiateAgree;
    private Button initiateSubmit;
    private InitiateDialog initiateDialog;

    private TextView initiate_money_pay, initiate_money_get;

    private int countMax, countMin;
    private TimePickerView startTimePicker, endTimePicker;
    private long timeStart, timeEnd;

    private String title, startLoc, endLoc, startTime, endTime, fee, /*destiny, */
            content, startCityId, endCityId/*, destinyId*/;
    //    private double venueLatitude, venueLongitude;
    private float balance;
    private String isEmpty;

    private HeadUploadPopup headUploadPopup;

    private File imageStore;

    private Map<String, String> mapPhoto;

    private String objectKey;
    private ImageView initiate_show_img1, initiate_show_img2, initiate_show_img3, initiate_show_img4;
    private Handler handler;
    private double latitude;
    double longitude;
    String address;
    private AlertDialog lawAlertDialog;
    private AccompanyInfoBean accompanyInfoBean;

    private boolean getBoolean;
    private boolean isImageUploading = false;
    private SimpleDateFormat formatter;
    private TimeSelector startTimeSelector,endTimeSelector;
    private long time = 0;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_activities_initiate);
        ((TextView) findViewById(R.id.common_title_text)).setText("发布活动");
        initiateTitle = (TextView) findViewById(R.id.initiate_title);
        initiateStartLoc = (TextView) findViewById(R.id.initiate_start_loc);
        initiateEndLoc = (TextView) findViewById(R.id.initiate_end_loc);
        initiateStartTime = (TextView) findViewById(R.id.initiate_start_time);
        initiateEndTime = (TextView) findViewById(R.id.initiate_end_time);
//        initiateVenue = (TextView) findViewById(R.id.initiate_venue);
        initiateFee = (EditText) findViewById(R.id.initiate_fee);
//        initiateDestination = (TextView) findViewById(R.id.initiate_destination);
        initiateUploadImg = (TextView) findViewById(R.id.initiate_upload_img);
        initiateAgreement = (TextView) findViewById(R.id.initiate_agreement);
        initiate_venue = (TextView) findViewById(R.id.initiate_venue);
        maxMinus = (ImageButton) findViewById(R.id.max_minus);
        minMinus = (ImageButton) findViewById(R.id.min_minus);
        maxAdd = (ImageButton) findViewById(R.id.max_add);
        minAdd = (ImageButton) findViewById(R.id.min_add);
        maxParticipant = (EditText) findViewById(R.id.max_participant);
        minParticipant = (EditText) findViewById(R.id.min_participant);
        initiateDetailIntro = (EditText) findViewById(R.id.initiate_detail_intro);
        venue01 = (TextView) findViewById(R.id.venue_01);
        initiateAgree = (CheckBox) findViewById(R.id.initiate_agree);
        initiateSubmit = (Button) findViewById(R.id.initiate_submit);
        initiateDialog = new InitiateDialog(ActivitiesInitiateActivity.this);

        initiate_money_pay = (TextView) findViewById(R.id.initiate_money_get);
        initiate_money_get = (TextView) findViewById(R.id.initiate_money_pay);

        initiate_show_img1 = (ImageView) findViewById(R.id.initiate_show_img1);
        initiate_show_img2 = (ImageView) findViewById(R.id.initiate_show_img2);
        initiate_show_img3 = (ImageView) findViewById(R.id.initiate_show_img3);
        initiate_show_img4 = (ImageView) findViewById(R.id.initiate_show_img4);

        initiate_show_img1.setVisibility(View.INVISIBLE);
        initiate_show_img2.setVisibility(View.INVISIBLE);
        initiate_show_img3.setVisibility(View.INVISIBLE);
        initiate_show_img4.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void initData() {


        getBoolean = true;
        mapPhoto = new HashMap<>();
        handler = new Handler(this);
        initiateAgreement.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

        countMax = Integer.valueOf(maxParticipant.getText().toString());
        Selection.setSelection(maxParticipant.getText(), maxParticipant.getText().length());

        countMin = Integer.valueOf(minParticipant.getText().toString());
        Selection.setSelection(minParticipant.getText(), minParticipant.getText().length());

        Calendar selectedDate = Calendar.getInstance();
        selectedDate.setTime(new Date());

        final Calendar startDate = Calendar.getInstance();
        startDate.set(selectedDate.get(Calendar.YEAR), selectedDate.get(Calendar.MONTH), selectedDate.get(Calendar.DATE), selectedDate.get(Calendar.HOUR_OF_DAY), selectedDate.get(Calendar.MINUTE));
        final Calendar endDate = Calendar.getInstance();
        endDate.set(selectedDate.get(Calendar.YEAR) + 20, selectedDate.get(Calendar.MONTH) + 20, selectedDate.get(Calendar.DATE) + 20, selectedDate.get(Calendar.HOUR_OF_DAY) + 20, selectedDate.get(Calendar.MINUTE) + 20);

        initiate_money_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getBoolean = true;
                initiate_money_pay.setBackgroundResource(R.drawable.shape_left_half_circle_orange);
                initiate_money_get.setBackgroundResource(R.drawable.shape_right_half_circle_gray);
            }
        });

        initiate_money_get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getBoolean = false;
                initiate_money_pay.setBackgroundResource(R.drawable.shape_left_half_circle_gray);
                initiate_money_get.setBackgroundResource(R.drawable.shape_right_half_circle_orange);
            }
        });

        if (formatter == null)
            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date();
        time = date.getTime();
        startTimeSelector = new TimeSelector(ActivitiesInitiateActivity.this, new TimeSelector.ResultHandler() {
            @Override
            public void handle(String time) {
                try {
                    timeStart =  formatter.parse(time).getTime();
                    initiateStartTime.setText(time);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }, formatter.format(new Date()), formatter.format(endDate.getTime()));

        endTimeSelector = new TimeSelector(ActivitiesInitiateActivity.this, new TimeSelector.ResultHandler() {
            @Override
            public void handle(String time) {
                try {
                    timeEnd =  formatter.parse(time).getTime();
                    initiateEndTime.setText(time);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }, formatter.format(new Date()), formatter.format(endDate.getTime()));

        /*startTimePicker = new TimePickerView.Builder(ActivitiesInitiateActivity.this,
                new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        timeStart = date.getTime();
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        String dateString = formatter.format(date);
                        initiateStartTime.setText(dateString);
                    }
                }).isDialog(true).setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN)
                .setRangDate(startDate, endDate).build();
        startTimePicker.setDate(Calendar.getInstance());*/

        /*endTimePicker = new TimePickerView.Builder(ActivitiesInitiateActivity.this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                timeEnd = date.getTime();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String dateString = formatter.format(date);
                initiateEndTime.setText(dateString);
            }
        }).isDialog(true).setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN)
                .setRangDate(startDate, endDate).build();*/

        headUploadPopup = new HeadUploadPopup(this, getWindow(), R.style.animBottomInBottomOut,
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        headUploadPopup.dismiss();
                        switch (view.getId()) {
                            case R.id.upload_photo:
                                if (isImageUploading) {
                                    ToastUtils.showToast("上传图片中，请稍后再试");
                                    break;
                                }
                                if (Build.VERSION.SDK_INT >= 23) {
                                    ActivitiesInitiateActivity.this.onRuntimePermissionRequest(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                                            new PermissionListener() {
                                                @Override
                                                public void onGranted() {
                                                    imageStore = new File(Environment.getExternalStorageDirectory(),
                                                            CommonData.STORAGE_PICTURE_FILE + System.currentTimeMillis() + ".jpg");
                                                    ImageHandleUtils.takePhoto(ActivitiesInitiateActivity.this, imageStore, TAKE_PHOTO);
                                                }

                                                @Override
                                                public void onDenied(List<String> deniedPermissions) {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            ToastUtils.showToast("调起摄像头失败！");
                                                        }
                                                    });
                                                }
                                            });
                                } else {
                                    imageStore = new File(Environment.getExternalStorageDirectory(),
                                            CommonData.STORAGE_PICTURE_FILE + System.currentTimeMillis() + ".jpg");
                                    ImageHandleUtils.takePhoto(ActivitiesInitiateActivity.this, imageStore, TAKE_PHOTO);
                                }
                                break;

                            case R.id.upload_album:
                                if (mapPhoto.size() >= 4) {
                                    ToastUtils.showToast("最多选择4张");
                                    break;
                                }
                                if (isImageUploading) {
                                    ToastUtils.showToast("上传图片中，请稍后再试");
                                    break;
                                }
                                getTakePhoto().onPickMultiple(4 - mapPhoto.size());
//                                if (Build.VERSION.SDK_INT >= 23) {
//                                    //写SD卡权限申请
//                                    BaseActivity.onRuntimePermissionRequest(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                                            new PermissionListener() {
//                                                @Override
//                                                public void onGranted() {
//                                                    imageStore = new File(Environment.getExternalStorageDirectory(),
//                                                            CommonData.STORAGE_PICTURE_FILE + System.currentTimeMillis() + ".jpg");
//                                                    ImageHandleUtils.openAlum(ActivitiesInitiateActivity.this, CHOOSE_IMAGE);
//                                                }
//
//                                                @Override
//                                                public void onDenied(List<String> deniedPermissions) {
//                                                    for (String p : deniedPermissions) {
//                                                        Toast.makeText(ActivityCollector.getTopActivity(),
//                                                                p + "权限被拒绝", Toast.LENGTH_SHORT).show();
//                                                    }
//                                                }
//                                            });
//                                } else {
//                                    imageStore = new File(Environment.getExternalStorageDirectory(),
//                                            CommonData.STORAGE_PICTURE_FILE + System.currentTimeMillis() + ".jpg");
//                                    ImageHandleUtils.openAlum(ActivitiesInitiateActivity.this, CHOOSE_IMAGE);
//                                }
                                break;

                            case R.id.upload_cancel:
                                headUploadPopup.dismiss();
                                break;
                            default:
                                break;
                        }
                    }
                });

        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Accompany_Info.getAccompanyInfo");
        CommonRequestNetData.getJsonObjectData(ActivitiesInitiateActivity.this, param, true, new CommonRequestNetData.JsonObjectCallBack() {
            Gson gson;

            @Override
            public void parseJsonObject(JSONObject jsonObject) {
                try {
                    LogUtils.e(TAG + "jsObj = " + jsonObject);
                    balance = (float) jsonObject.getDouble("member_balance");
                    gson = new Gson();
                    accompanyInfoBean = gson.fromJson(jsonObject.toString(), AccompanyInfoBean.class);
                    LogUtils.e(TAG + "balance = " + balance);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void loadNetData() {

    }

    @Override
    protected void setListener() {
        findViewById(R.id.common_back).setOnClickListener(this);
        findViewById(R.id.common_home_back).setOnClickListener(this);
        initiateTitle.setOnClickListener(this);
        initiateStartLoc.setOnClickListener(this);
        initiateEndLoc.setOnClickListener(this);
        initiateStartTime.setOnClickListener(this);
        initiateEndTime.setOnClickListener(this);
        initiate_venue.setOnClickListener(this);
//        initiateVenue.setOnClickListener(this);
        maxMinus.setOnClickListener(this);
        maxAdd.setOnClickListener(this);
        minMinus.setOnClickListener(this);
        minAdd.setOnClickListener(this);
//        initiateFee.setOnClickListener(this);
//        initiateDestination.setOnClickListener(this);
        initiateUploadImg.setOnClickListener(this);
        initiateAgreement.setOnClickListener(this);
        initiateSubmit.setOnClickListener(this);
        venue01.setOnClickListener(this);
        maxParticipant.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextCheckUtils.checkIsNumber(charSequence.toString())) {
                    ToastUtils.showToast("请输入数字");
                    maxParticipant.setText("0");
                } else if (maxParticipant.getText().toString().equals("")) {
                    countMax = 0;
                } else {
                    countMax = Integer.valueOf(maxParticipant.getText().toString());
                    Selection.setSelection(maxParticipant.getText(), maxParticipant.getText().length());
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        minParticipant.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextCheckUtils.checkIsNumber(charSequence.toString())) {
                    ToastUtils.showToast("请输入数字");
                    minParticipant.setText("0");
                } else if (minParticipant.getText().toString().equals("")) {
                    countMin = 0;
                } else {
                    countMin = Integer.valueOf(minParticipant.getText().toString());
                    Selection.setSelection(minParticipant.getText(), minParticipant.getText().length());
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        initiateDialog.setOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap<String, String> param = new HashMap<>();
                param.put("service", "Conductor_Activity.add");
                param.put("title", StringEscapeUtils.escapeJava(title));
                param.put("start_address", startCityId);
                param.put("end_address", endCityId);
                param.put("gather_address", venue01.getText().toString());

                param.put("start_time", timeStart / 1000 + "");
                param.put("end_time", timeEnd / 1000 + "");
                param.put("min_people", minParticipant.getText().toString());
                param.put("max_people", maxParticipant.getText().toString());

                if (!getBoolean) {
                    fee = "-" + fee;
                    if (Integer.parseInt(maxParticipant.getText().toString()) == 0) {
                        ToastUtils.showToast("最大参与人数必须大于0人");
                    }
                }

                if (fee.equals("0")) {
                    fee = "-" + fee;
                }

                param.put("price", fee);
                param.put("content",StringEscapeUtils.escapeJava(initiateDetailIntro.getText().toString()) );
//                param.put("tactivity_city_id", destinyId);
                param.put("longitude", longitude + "");
                param.put("latitude", latitude + "");
                Gson gson = new Gson();
                if (mapPhoto.size() > 0) {
                    List<String> array = new ArrayList<String>();
                    for (String key : mapPhoto.keySet()) {
                        array.add(key);
                    }
                    String temp = gson.toJson(array).replace("\"", "").replace("]", "").replace("[", "");
                    LogUtils.d(temp);
                    param.put("tactivity_picture_list", gson.toJson(array).replace("\"", "").replace("]", "").replace("[", ""));
                }

                LogUtils.e(TAG + "param = " + param.toString());

                CommonRequestNetData.getJsonStringData(ActivitiesInitiateActivity.this, param, true, new CommonRequestNetData.JsonStringCallBack() {
                    @Override
                    public void parseJsonString(String str) {
                        LogUtils.e(TAG + "str = " + str);
                        initiateDialog.dismiss();
                        MyActivitiesActivity.startActivities(ActivitiesInitiateActivity.this, 0);
                        ActivityCollector.removeActivity(ActivitiesInitiateActivity.this);
                    }
                }, new CommonRequestNetData.MinusStringCallBack() {
                    @Override
                    public void minusJson(String string) throws Exception {
                        if (!TextCheckUtils.isEmpty(string)) {
                            ToastUtils.showToast(string);
                        }
                        startActivity(new Intent(ActivitiesInitiateActivity.this, BalanceNotEnoughActivity.class));
                    }
                });

            }
        });
    }

    private String judgeEmpty() {
        title = initiateTitle.getText().toString();
        startLoc = initiateStartLoc.getText().toString();
        endLoc = initiateEndLoc.getText().toString();
        startTime = initiateStartTime.getText().toString();
        endTime = initiateEndTime.getText().toString();
        fee = initiateFee.getText().toString();
//        venue = initiateVenue.getText().toString();
//        destiny = initiateDestination.getText().toString();
        content = initiateDetailIntro.getText().toString();

        if (TextUtils.isEmpty(title) || TextUtils.equals(title, "请输入标题")) {
            return "标题不能为空";
        } else if (TextUtils.isEmpty(startLoc) || TextUtils.equals(startLoc, "始发地")) {
            return "请选择始发地点";
        } else if (TextUtils.isEmpty(endLoc) || TextUtils.equals(endLoc, "目的地")) {
            return "请选择目的地";
        } else if (TextUtils.isEmpty(startTime) || TextUtils.equals(startTime, "请选择时间")) {
            return "开始时间不能为空";
        } else if (TextUtils.isEmpty(endTime) || TextUtils.equals(endTime, "请选择时间")) {
            return "开始时间不能为空";
        } else if (TextUtils.isEmpty(venue01.getText().toString())) {
            return "集合地点不能为空";
        } else if (TextUtils.isEmpty(fee)) {
            return "活动费用不能为空";
        } /*else if (TextUtils.isEmpty(destiny) || TextUtils.equals(destiny, "请选择城市")) {
            return "城市不能为空";
        }*/ else if (TextUtils.isEmpty(content)) {
            return "请输入详情介绍";
        } else if (timeStart > timeEnd) {
            return "开始时间不能大于结束时间";
        }

        if (Integer.parseInt(maxParticipant.getText().toString()) != 0) {
            if (Integer.parseInt(minParticipant.getText().toString()) > Integer.parseInt(maxParticipant.getText().toString())) {
                return "最小参与人数不能大于最大参与人数";
            }
        }

        return "";

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case GET_TITLE:
                    initiateTitle.setText(data.getStringExtra("data_return"));
                    break;
                case GET_START_LOC:
                    initiateStartLoc.setText(data.getStringExtra("city_name"));
                    startCityId = data.getStringExtra("city_id");
                    break;
                case GET_END_LOC:
                    initiateEndLoc.setText(data.getStringExtra("city_name"));
                    endCityId = data.getStringExtra("city_id");
                    break;
                case TAKE_PHOTO:
                    showCropImage(data);
                    break;
//                case CHOOSE_IMAGE:
//                    ImageHandleUtils.startCropImage(ActivitiesInitiateActivity.this,
//                            data.getData(), CROP_IMAGE, 1, 1, 200, 200);
//                    break;
//                case CROP_IMAGE:
//                    if (data != null) {
//                        LogUtils.e(TAG + "after crop");
//                        showCropImage(data);
//                    }
//                    break;
//                case GET_FEE:
//                    initiateFee.setText(data.getStringExtra("data_return").trim());
//                    break;
//                case GET_DESTINATION:
//                    initiateDestination.setText(data.getStringExtra("city_name"));
//                    destinyId = data.getStringExtra("city_id");
//                    break;
                case GET_VENUE:
                    address = data.getStringExtra("loc_address");
                    latitude = data.getDoubleExtra("latitude", 0.0);
                    longitude = data.getDoubleExtra("longitude", 0.0);
                    LogUtils.e(TAG + "address = " + data.getStringExtra("loc_address"));
                    venue01.setText(address);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        for (TImage tImage : result.getImages())
            uploadImage(tImage);
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    private void uploadImage(TImage images) {
        try {
            String photoPath = images.getCompressPath();
            if (TextUtils.isEmpty(photoPath))
                photoPath = images.getOriginalPath();

            objectKey = "temp/" + System.currentTimeMillis() + ".jpg";
            OssUtils.uploadPic(photoPath, objectKey, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
                    isImageUploading = false;
                }

                @Override
                public void onFailure(PutObjectRequest putObjectRequest, ClientException e, ServiceException e1) {
                    isImageUploading = false;
                    ToastUtils.showToast("图片上传失败！请稍后再试");
                }
            }, new OssUtils.onPhotoUploadResult() {
                @Override
                public void onResult(String key, String path) {
                    mapPhoto.put(key, path);
                    handler.sendEmptyMessage(1);
                }

                @Override
                public void onProgress(long currentSize, long totalSize) {
                    if(currentSize >= totalSize){
                        isImageUploading = false;
                    }else{
                        isImageUploading = true;
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void showCropImage(Intent data) {

        try {
            String path = imageStore.getPath();
            Bitmap compressPhoto = CompressPhoto.compressBySize(imageStore.getPath(),800,800);

            if (compressPhoto != null) {
                CompressPhoto.saveFile(compressPhoto, imageStore.getPath());
            }


            objectKey = "temp/" + System.currentTimeMillis() + ".jpg";
            OssUtils.uploadPic(path, objectKey, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
                    isImageUploading = false;
                }

                @Override
                public void onFailure(PutObjectRequest putObjectRequest, ClientException e, ServiceException e1) {
                    isImageUploading = false;
                    ToastUtils.showToast("图片上传失败！请稍后再试");
                }
            }, new OssUtils.onPhotoUploadResult() {
                @Override
                public void onResult(String key, String filePath) {
                    mapPhoto.put(key, filePath);
                    handler.sendEmptyMessage(1);
                }

                @Override
                public void onProgress(long currentSize, long totalSize) {
                    if(currentSize >= totalSize){
                        isImageUploading = false;
                    }else{
                        isImageUploading = true;
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void update() {
        int i = 0;
        if (mapPhoto.size() == 4) {
            initiateUploadImg.setVisibility(View.INVISIBLE);
        }
        Map<String, String> map = new HashMap<>();
        map.putAll(mapPhoto);
        for (String key : map.keySet()) {

            LogUtils.d(key + "|" + mapPhoto.get(key));
            switch (i) {
                case 0:
                    Glide.with(ActivitiesInitiateActivity.this).load(mapPhoto.get(key)).into(initiate_show_img1);
                    initiate_show_img1.setVisibility(View.VISIBLE);
                    break;
                case 1:
                    Glide.with(ActivitiesInitiateActivity.this).load(mapPhoto.get(key)).into(initiate_show_img2);
                    initiate_show_img2.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    Glide.with(ActivitiesInitiateActivity.this).load(mapPhoto.get(key)).into(initiate_show_img3);
                    initiate_show_img3.setVisibility(View.VISIBLE);
                    break;
                case 3:
                    Glide.with(ActivitiesInitiateActivity.this).load(mapPhoto.get(key)).into(initiate_show_img4);
                    initiate_show_img4.setVisibility(View.VISIBLE);
                    break;
            }
            i++;
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                ActivityCollector.removeActivity(this);
                break;

            case R.id.common_home_back:
                startActivity(new Intent(ActivitiesInitiateActivity.this, MainActivity.class));
                ActivityCollector.removeActivity(this);
                break;

            case R.id.initiate_title:
                startActivityForResult(new Intent(ActivitiesInitiateActivity.this, TextInputActivity.class), GET_TITLE);
                break;

            case R.id.initiate_start_loc:
                startActivityForResult(new Intent(ActivitiesInitiateActivity.this, CitySelectActivity.class), GET_START_LOC);
                break;

            case R.id.initiate_end_loc:
                startActivityForResult(new Intent(ActivitiesInitiateActivity.this, CitySelectActivity.class), GET_END_LOC);
                break;

            case R.id.initiate_start_time:
                startTimeSelector.show();
                break;

            case R.id.initiate_end_time:
                endTimeSelector.show();
                break;

            case R.id.initiate_venue:
                if (Build.VERSION.SDK_INT >= 23) {
                    BaseActivity.onRuntimePermissionRequest(new String[]{Manifest.permission.ACCESS_FINE_LOCATION  }, new PermissionListener() {
                        @Override
                        public void onGranted() {
                            startActivityForResult(new Intent(ActivitiesInitiateActivity.this, AddressSelectActivity.class), GET_VENUE);
                        }

                        @Override
                        public void onDenied(List<String> deniedPermissions) {
                            ToastUtils.showToast("需要定位的权限，请到权限管理打开该权限！");
                        }
                    });
                }else{
                    startActivityForResult(new Intent(ActivitiesInitiateActivity.this, AddressSelectActivity.class), GET_VENUE);
                }
                break;

            case R.id.max_minus:
                if (countMax == 0) {
                    ToastUtils.showToast("人数不能小于0");
                } else {
                    --countMax;
                    maxParticipant.setText(countMax + "");
                }
                break;

            case R.id.max_add:
                ++countMax;
                maxParticipant.setText(countMax + "");
                break;

            case R.id.min_minus:
                if (countMin == 0) {
                    ToastUtils.showToast("人数不能小于0");
                } else {
                    --countMin;
                    minParticipant.setText(countMin + "");
                }
                break;

            case R.id.min_add:
                ++countMin;
                minParticipant.setText(countMin + "");
                break;

            case R.id.initiate_fee:
                startActivityForResult(new Intent(ActivitiesInitiateActivity.this, TextInputActivity.class), GET_FEE);
                break;

//            case R.id.initiate_destination:
//                startActivityForResult(new Intent(ActivitiesInitiateActivity.this, CitySelectActivity.class), GET_DESTINATION);
//                break;

            case R.id.initiate_upload_img:
                headUploadPopup.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                CommonMethod.setWindowAlpha((float) 0.5, getWindow());
                break;

            case R.id.initiate_agreement://法律条文
                BaseParam agreementParam = new BaseParam("Public_UserIndex.getSinglePageUrl");
                agreementParam.put("service", "Public_UserIndex.getSinglePageUrl");
                agreementParam.put("article_type", "agreement");
                agreementParam.put("client", "accompany");
                CommonRequestNetData.getJsonObjectData(this, agreementParam.getParam(), false, new CommonRequestNetData.JsonObjectCallBack() {
                    @Override
                    public void parseJsonObject(JSONObject jsonObject) {
                        try {
                            String url = jsonObject.getString("URL");
                            Intent intent = new Intent(ActivitiesInitiateActivity.this, BrowserActivity.class);
                            intent.putExtra("url", url);
                            startActivity(intent);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                break;
            case R.id.initiate_submit:
                if (isImageUploading) {
                    ToastUtils.showToast("上传图片中，请稍后再试");
                    break;
                }
                isEmpty = judgeEmpty();
                if (!initiateAgree.isChecked()) {
                    ToastUtils.showToast("需要同意约定条款才能发布哦~");
                } else if (!isEmpty.equals("")) {
                    ToastUtils.showToast(isEmpty);
                } else {
                    if (initiateFee.getText().toString().startsWith("-")) {
                        LogUtils.e(TAG + "负数发起");

                        if (Float.valueOf(initiateFee.getText().toString().split("-")[1]) > balance) {
                            ToastUtils.showToast("余额不足，请前往充值");
                            startActivity(new Intent(ActivitiesInitiateActivity.this, BalanceNotEnoughActivity.class));
                        } else {
                            initiateDialog.show();
                        }
                    } else {
                        LogUtils.e(TAG + "正数发起");
                        initiateDialog.show();
                    }
                }
                break;
            case R.id.initiate_show_img1:
                break;
            case R.id.initiate_show_img2:
                break;
            case R.id.initiate_show_img3:
                break;
            case R.id.initiate_show_img4:
                break;
            default:
                break;
        }
    }

    @Override
    public boolean handleMessage(Message message) {
        if (message.what == 1) {
            update();
        }
        return false;
    }
}
